package com.zxy.service;

import cn.echo.threadlocal.LocalUserUtils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zxy.dao.IoItemDao;
import com.zxy.dao.IoMasterDao;
import com.zxy.dao.PoMasterDao;
import com.zxy.enums.PoMasterStatus;
import com.zxy.model.*;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class IoService {

    @Autowired
    private IoMasterDao ioMasterDao;
    @Autowired
    private IoItemDao ioItemDao;
    @Autowired
    private PoMasterDao poMasterDao;

    @Autowired
    private InventoryService inventoryService;

    public int insert(IoMaster master) {
//        单号 后端生成
        String  ioId = "IO"+ DateUtil.format(DateUtil.date(),"yyyyMMddHHmmssSSS");
        master.setId(ioId);
        master.setWPerson(LocalUserUtils.get().getNickName());
//        获取当前时间
        master.setIoDate(LocalDateTimeUtil.now().toLocalDate());

        List<IoItem> items = master.getItems();
        for(IoItem item : items){
            item.setIoId(ioId);
//            setLastUpdateBy 批量进行插入，拦截器不会进行拦截
            item.setLastUpdateBy(LocalUserUtils.get().getNickName());
        }
//      代理
        IoService service =   (IoService) AopContext.currentProxy();
        service.add(master);

        return  1;
    }

    @Transactional
    public void  add(IoMaster master){
        ioMasterDao.insert(master);
        List<IoItem> items = master.getItems();
//        批量去插入
        ioItemDao.insert(items);
        for(IoItem item : items){
            InventoryLog inventoryLog = new InventoryLog();
            inventoryLog.setOptionQty(item.getQty());
            inventoryLog.setProductId(item.getProductId());
            inventoryLog.setOptionType(1);
//            第三方单据
            inventoryLog.setRefId(master.getId());
            inventoryLog.setProductName(item.getProductName());
            inventoryLog.setExpirationDay(item.getExpirationDay());
            inventoryLog.setProductionDate(item.getProductionDate());
            inventoryLog.setShelfId(item.getShelfId());
            inventoryService.option(inventoryLog);
        }
        PoMaster poMaster = new PoMaster();
        poMaster.setId(master.getId());
        poMaster.setStatus(PoMasterStatus.COMPLETE.getCode());
        poMasterDao.update(poMaster);
    }
    public List<IoMaster> select(IoMasterQuery query) {
        return  ioMasterDao.select(query);
    }

    public List<IoItem> selectItem(IoItemQuery query) {
        return ioItemDao.select(query);
    }
}